// Author: Domien Nowicki

#include "CameraWidget.h"
#include <QGraphicsSceneMouseEvent>
#include <QPainter>
#include <QStyleOption>
#include <math.h>

CameraWidget::CameraWidget(QObject *parent): QObject(parent), highlight(false), angle(0), canRotate(false)
{
	setAcceptsHoverEvents(true);
	setZValue(3);
}



CameraWidget::~CameraWidget()
{
}

QRectF CameraWidget::boundingRect() const
{
	return QRectF(0, 0, BOXSIZE, BOXSIZE);
}

QPainterPath CameraWidget::shape() const
{
	QPainterPath path;

	path.addEllipse(0, 0, BOXSIZE, BOXSIZE);
	return path;
}

void CameraWidget::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	QColor color = Qt::green;

	// Draw the green ellipse
	painter->setPen(Qt::NoPen);
	painter->setBrush(color);
	painter->drawEllipse(0, 0, BOXSIZE, BOXSIZE);

	// Draw the yellow camera angle "pie"
	painter->setBrush(Qt::yellow);
	painter->drawPie(0,0, BOXSIZE, BOXSIZE, -angle.GetInt()-(ANGLESIZE/2)*16, ANGLESIZE*16);

	if (highlight)
	{
		color = Qt::white;
		color.setAlpha(100);

		// White highlighting
		painter->setBrush(color);
		painter->drawEllipse(0, 0, BOXSIZE, BOXSIZE);
	}
}

void CameraWidget::hoverEnterEvent(QGraphicsSceneHoverEvent *e)
{
 	highlight = true;

	update();
}

void CameraWidget::hoverLeaveEvent(QGraphicsSceneHoverEvent *e)
{
	highlight = false;

	update();
}

// Only allow rotation when it is set
void CameraWidget::EnableRotation()
{
	canRotate = true;
}

void CameraWidget::DisableRotation()
{
	canRotate = false;
}

void CameraWidget::mouseMoveEvent(QGraphicsSceneMouseEvent *e)
{
	if (!canRotate)
	{
		return;
	}

	// Offset to center of circle
	double camX = ((double)BOXSIZE)/2;
	double camY = ((double)BOXSIZE)/2;

	// Calculate mouse pointer coordinates from center of the circle
	double x = e->pos().x() - camX;
	double y = e->pos().y() - camY;

	// Prevent divide by zero
	if (-0.1 <= x && x <= 0.1)
		x = 0.1;

	// Ratio for atan
	double ratio = y/x;
	double anglef = atan( ratio ) * 180 /  3.14159265; // in degrees
	// Fixup according to which quadrant the mouse pointer coordinates were in
	if (x < 0)
		anglef += 180.0f;

	// Set new angle
	SetAngle(anglef);

	// Emit signal with normal degree angle (converts 1/16th degree angle into normal degree)
	emit rotated(angle/16);
}

void CameraWidget::mousePressEvent(QGraphicsSceneMouseEvent *e)
{
	emit clicked();
}

unsigned int CameraWidget::GetWidth() const
{
	return BOXSIZE;
}

unsigned int CameraWidget::GetHeight() const
{
	return BOXSIZE;
}

void CameraWidget::SetAngle(const Scalar& nAngle)
{
	// Multiply by 16 to convert decimal angle into integer angle (Qt uses 1/16th degree)
	angle = nAngle*16;
	angle.ConvertToInteger();

	update();
}

const Scalar& CameraWidget::GetAngle() const
{
	return angle;
}
